package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.ErrorCode;
import com.example.demo.constant.CommonConstant;
import com.example.demo.context.UserContext;
import com.example.demo.entity.Expert;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.ExpertMapper;
import com.example.demo.service.ExpertService;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.MD5Utils;
import com.example.demo.vo.UserLoginVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.prefs.BackingStoreException;

/**
 * 专家表(Expert)表服务实现类
 *
 * @author makejava
 * @since 2025-01-28 12:22:31
 */
@Service
@RequiredArgsConstructor
public class ExpertServiceImpl extends ServiceImpl<ExpertMapper, Expert> implements ExpertService {
    private final JwtUtils jwtUtils;

    @Override
    public List<Expert> listAll() {
        LambdaQueryWrapper<Expert>lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Expert::getStatus,1);
        List<Expert> list = list(lambdaQueryWrapper);
            return list;
    }

    @Override
    public UserLoginVo login(String username, String password) {
        Expert expert = getOne(new LambdaQueryWrapper<Expert>().eq(Expert::getUsername, username)); 
        if (expert == null) {
            throw new BusinessException(ErrorCode.ACCOUNT_NOT_EXIST);
        }
        if (!MD5Utils.verify(password, expert.getPassword())) {
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }
        Map<String,Object>map=new ConcurrentHashMap<>();
        map.put("id",expert.getId());
        map.put("username",expert.getUsername());
        String token = jwtUtils.generateToken(map, CommonConstant.UserType.EXPERT);
        return UserLoginVo.builder().token(token).build();
    }

    @Override
    public void updateStatus(Integer status) {
        Expert expert=new Expert();
        expert.setId(UserContext.getUserId());
        expert.setStatus(status);
        updateById(expert);
    }
}
